/*
 * Copyright notice
 */

package com.gtd.util
import groovy.xml.MarkupBuilder

/**
 *
 * @author hoatle
 * @since  1.0
 * @since  Jul 17, 2009
 *
 */
class HashMapToXML {
  static listTag = "item"
  static convert(map) {
    def writer = new StringWriter()
    def xml = new MarkupBuilder(writer)
    //TODO: Refine this to more general
    def rootEntry = map.entrySet().toArray()[0]
    def root = xml.createNode(rootEntry.key)
    setNode(xml, rootEntry.value, null, root)
    xml.nodeCompleted(null, root)
    writer.toString()
  }

  private static setNode(xml, map, previousParent, currentParent) {
    for (child in map) {
      if (child.value == null) {
        child.value = ""
      }
      if (child.value.getClass() == Integer || child.value.getClass() == Long) {
        child.value = child.value.toString()
      }
      if (child.value.getClass() == String) {
        def node = xml.createNode(child.key, child.value)
        xml.nodeCompleted(currentParent, node)
      } else if (child.value.getClass() == LinkedHashMap) {
        //LinkedHashMap
        def pr = xml.createNode(child.key)
        setNode(xml, child.value, currentParent, pr)
        xml.nodeCompleted(previousParent, pr)
      } else if (child.value.getClass() == ArrayList){

        def pr = xml.createNode(child.key)
        for (c in child.value) {
          if (c.value == null) c.value = ""
          if (c.value.getClass() == Integer) c.value = c.value.toString()
          //When c is empty arr
          if (c.getClass() == String) {
            def node = xml.createNode(HashMapToXML.listTag, c)
            xml.nodeCompleted(pr, node)
          } else if (c.getClass() == LinkedHashMap) {
            def cRootEntry = c.entrySet().toArray()[0]
            def newParent = xml.createNode(cRootEntry.key)
            setNode(xml, cRootEntry.value, pr, newParent)
            xml.nodeCompleted(pr, newParent)

          } else if (c.getClass() == ArrayList) {
            //TODO: Should handle this for public use
          }
        }
        xml.nodeCompleted(previousParent, pr)
      }
    }
  }
}

